import { noop } from '@/utils/fn';
import useStorage from '@/utils/hooks/useStorage';
import { View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { HISTORY_STORAGE_KEY, SearchStatus } from './constants';
import History from './History';
import styles from './index.module.scss';
import Search from './Search';

const StandSearch = ({
  // 初始搜索状态
  defaultSearchStatus = SearchStatus.history,
  // 立即搜索内容
  defaultValue,
  // 触发搜索
  onSearch,
  // 搜索结果展示
  children,

  allowEmpty = false,
  onFocus = noop,
  ...searchProps
}) => {
  const [history, setHistory] = useStorage(HISTORY_STORAGE_KEY, []);

  // 搜索状态, => 搜索历史/搜索结果
  const [status, setStatus] = useState(defaultSearchStatus);

  // 搜索框 value
  const [searchValue, setSearchValue] = useState(defaultValue);

  // 接口请求的 搜索 value
  const searchValueRef = useRef();

  // 1. 判断显示 搜索历史还是搜索结果
  // 2. 设置 searchValue
  const handleChange = useCallback(
    (v) => {
      if (v?.length && v === searchValueRef.current) {
        // 置为搜索结果状态
        console.log('debug for search status change', '输入内容变化', SearchStatus.result);
        setStatus(SearchStatus.result);
      } else {
        // 置为搜索历史
        console.log('debug for search status change', '输入内容变化', SearchStatus.history);
        setStatus(SearchStatus.history);
      }

      setSearchValue(v);
    },
    [searchValueRef],
  );

  // 搜商品
  const handleConfirm = useCallback(
    async (v) => {
      if (!v && !allowEmpty) {
        Taro.showToast({
          title: '请输入关键字',
          duration: 2000,
          icon: 'none',
        });
        return;
      }

      // 置为搜索结果状态
      console.log('debug for search status change', '确认搜索', SearchStatus.result);
      setStatus(SearchStatus.result);

      // 设置当前搜索值
      searchValueRef.current = v;

      // 记录到历史搜索中
      setHistory([...new Set([v, ...history])].filter((s) => !!s).slice(0, 30));

      // 请求接口
      await onSearch({ value: searchValueRef.current });
    },
    [history],
  );

  const handleFocus = useCallback(() => {
    console.log('debug for search status change', 'focus', SearchStatus.history);
    setStatus(SearchStatus.history);
    onFocus();
  }, []);

  // 存在搜索字段, 立即搜索
  useEffect(() => {
    if (defaultValue) {
      handleConfirm(defaultValue);
    }
  }, [defaultValue]);

  console.log('debug for search status', {
    status,
    searchValue,
    apiValue: searchValueRef.current,
  });

  return (
    <View className={styles.StandSearch}>
      <View className="search-wrap">
        <Search
          className="stand-search"
          defaultValue={defaultValue}
          onConfirm={handleConfirm}
          placeholder="搜索商品"
          showBtn
          value={searchValue}
          onChange={handleChange}
          onFocus={handleFocus}
          {...searchProps}
        />
      </View>

      <View className="search-container">
        {status === SearchStatus.history && (
          <History
            {...{
              history,
              onClear: () => {
                setHistory([]);
              },
              onSearch: (v) => {
                handleChange(v);
                handleConfirm(v);
              },
            }}
          />
        )}

        {status === SearchStatus.result && children}
      </View>
    </View>
  );
};

export default StandSearch;
